package com.damai.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.citywithincity.utils.ClassUtil;
import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.JsonUtil;
import com.damai.utils.CtClassBuilder;

import javassist.Modifier;

public class ApiInterfaces extends BaseServiceAction{

	public static final String CREATE = "100";
	
	
	private Map<String, InterfaceAction> map = new ConcurrentHashMap<String, InterfaceAction>();
	
	
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	public ApiInterfaces(String key) {
		super(key);
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//json
		String content = IoUtil.readAndClose(new BufferedReader(request.getReader()));
		Map<String, Object> json = JsonUtil.read(content);
		String type = (String) json.get("type");
		
		if(type.equals(CREATE)){
			InterfaceAction action = null;
			String key = (String)json.get("key");
			String body = (String) json.get("body");
			String fields = (String)json.get("field");
			String constructor = (String)json.get("constructor");
			//创建一个规则
			CtClassBuilder builder = new CtClassBuilder("Api" + key + "_" + System.currentTimeMillis());
			try {
				
				if(fields!=null){
					String[] args = fields.split(",");
					for (String string : args) {
						builder.addField(string,Modifier.PUBLIC);
					}
				}
				
				if(constructor!=null){
					builder.addContructor(constructor);
					
				}
				
				builder.beginInterface(InterfaceAction.class);
				Method[] methods = ClassUtil.getPublicMethods(InterfaceAction.class);
				for (Method method : methods) {
					builder.beginMethod(method).setBody(body);
					builder.endMethod();
				}
				builder.make();
				action = builder.newInstance(); 
			} catch (Exception e) {
				e.printStackTrace(response.getWriter());
				return;
			}
			try{
				lock.writeLock().lock();
				map.put(key, action);
			}finally {
				lock.writeLock().unlock();
			}
			response.getWriter().print(JsonUtil.success(true));
		}else{
			InterfaceAction action = null;
			try{
				lock.readLock().lock();
				action = map.get(type);
			}finally {
				lock.readLock().unlock();
			}
			
			if(action!=null){
				Object result = action.execute(json);
				response.getWriter().print(JsonUtil.success(result));
			}else{
				response.getWriter().print(JsonUtil.alert("No Interface"));
			}
		}
		
	}

}
